﻿using System;

namespace CoreLibrary {

    public sealed class Util {

        public static string GetString(object value) {
            return GetString(value, string.Empty);
        }

        public static string GetString(object value, string def) {
            return value == null ? def : value.ToString();
        }

        public static string GetString(Func<string> func) {
            return GetString(func, string.Empty);
        }

        public static string GetString(Func<string> func, string def) {
            try {
                return GetString(func.Invoke, def);
            } catch {
                return def;
            }
        }

        public static double GetDouble(object value) {
            return GetDouble(value, 0.0);
        }

        public static double GetDouble(Func<double> func, double def) {
            try {
                return GetDouble(func.Invoke, def);
            } catch {
                return def;
            }
        }

        public static double GetDouble(object value, double def) {
            if (value == null) {
                return def;
            }

            if (value is double) {
                return (double) value;
            }

            var val = value.ToString();
            if (string.IsNullOrEmpty(val)) {
                return def;
            }

            double result;
            var o = double.TryParse(val, out result);
            return o ? result : def;
        }

        public static int GetInt(object value) {
            return GetInt(value,0);
        }

        public static int GetInt(Func<int> func, int def) {
            try {
                return GetInt(func.Invoke, def);
            } 
            catch {
                return def;
            }
        }

        public static int GetInt(object value, int def) {
            if (value == null) {
                return def;
            }

            if (value is int) {
                return (int) value;
            }

            var val = value.ToString();
            if (string.IsNullOrEmpty(val)) {
                return def;
            }

            int r;
            var o = int.TryParse(val, out r);
            return o ? r : def;
        }

    }
}